package com.magima.core.app;


import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.util.LongSparseArray;

public abstract class BaseFragmentActivity extends FragmentActivity {
	protected BaseApplication app;
	protected boolean mIsActivated;
	private LongSparseArray<Thread> mTasks;
	
	private static OnResumeCallback onResumeCallback = null;
	private static OnPauseCallback onPauseCallback = null;
	
	@Override
	protected void onCreate(Bundle bundle){
		super.onCreate(bundle);
		app = BaseApplication.fromContext(this);
		mTasks = new LongSparseArray<Thread>();	
		app.pushActivity(this);
	}

	@Override
	protected void onDestroy() {
		app.popActivity(this);
		super.onDestroy();
	}
	
	public void addTask(Thread task) {
		synchronized ( mTasks ){
			mTasks.put(task.getId(), task);
		}
	}
	
	public void removeTask(Thread task) {
		synchronized ( mTasks ){
			mTasks.remove(task.getId());
		}
	}
	
	@Override
	public void startActivity(Intent intent) {
		Object isForce = app.getData().get(BaseApplication.KEY_FORCE_UPDATE);
		if(isForce == null || !(Boolean)isForce){
			try {
				super.startActivity(intent);
			} catch ( ActivityNotFoundException e) {
				if ( app.getActivityNotFoundExceptionHandler() != null )
					app.getActivityNotFoundExceptionHandler().onException(this, e);
			}
		}
	}
	
	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		Object isForce = app.getData().get(BaseApplication.KEY_FORCE_UPDATE);
		if(isForce == null || !(Boolean)isForce){
			try {
				super.startActivityForResult(intent, requestCode);
			} catch ( ActivityNotFoundException e) {
				if ( app.getActivityNotFoundExceptionHandler() != null )
					app.getActivityNotFoundExceptionHandler().onException(this, e);
			}
		}
	}
	
	@Override
	public void onResume(){
		mIsActivated = true;
		super.onResume();
		if ( app.isDead() ) {
			finish();
			return;
		}
				
		if ( onResumeCallback != null )
			onResumeCallback.onResume(this);
		
		app.getAnalystsTool().onPageStart(this.getClass().getName());
		app.getAnalystsTool().onResume(this);
	}
	
	@Override
	public void onPause(){
		mIsActivated = false;
		super.onPause();		
		synchronized ( mTasks ){
			for ( int i =0 , size = mTasks.size(); i < size; i++ ){
				Thread task = (Thread) mTasks.valueAt(i);
				if(task.isAlive())
					task.interrupt();
			}
			mTasks.clear();
		}
		
		if ( onPauseCallback != null )
			onPauseCallback.onPause(this);
		
		app.getAnalystsTool().onPageEnd(this.getClass().getName());
		app.getAnalystsTool().onPause(this);
	}
	
	final static public void injectOnResume(OnResumeCallback callback){
		onResumeCallback = callback;
	}
	final static public void injectOnPause(OnPauseCallback callback){
		onPauseCallback = callback;
	}
}
